﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Net;

using System.IO;
using System.Drawing;

namespace DreamBox.Net
{
    public class HttpWebRequest
    {
        
        public HttpWebRequest()
        { }
        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="param">需要传输的参数(多个参数之间用&隔开)</param>
        /// <returns></returns>
        public object HttpPost(string url,string param)
        {
            object result = "";
            Stream reqStream = null;
            Stream resStream = null;
            try
            {
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";

                //处理参数
                byte[] b = Encoding.UTF8.GetBytes(param);

                request.ContentLength = b.Length;

                reqStream = request.GetRequestStream();

                reqStream.Write(b, 0, b.Length);
                //获取返回的输出对象
                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

                resStream = response.GetResponseStream();

                StreamReader reader = new StreamReader(resStream);
                result = reader.ReadToEnd();
                reqStream.Dispose();
                resStream.Dispose();
            }
            catch (Exception e)
            {
                result = e.Message;
            }
            return result;
        }
        /// <summary>
        /// 普通GET请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <returns></returns>
        public object HttpGet(string url)
        {
            object result = "";
            Stream stream = null;
            try
            {
                //加载请求类
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                request.Method = "GET";
               
                //获取返回的输出对象
                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

                //获取来自服务器响应的字符流
                stream = response.GetResponseStream();
                //读取返回的结果
                StreamReader reader = new StreamReader(stream);

                result = reader.ReadToEnd();
            }
            catch 
            {
 
            }
            finally
            {
                stream.Dispose();
            }
            return result;
        }
    }
}
